<template>
  <div class="form-container">
    <el-row :gutter="15">
      <el-col
        :xs="24"
        :sm="24"
        :md="12"
        :lg="8"
        :xl="8"
      >
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :status-icon="true"
        >
          <el-form-item
            v-if="user.level < 3"
            label="所属村"
            prop="villageWrap"
          >
            <el-cascader
              v-model="ruleForm.villageWrap"
              :options="villageCascader"
              :props="villageProp"
              placeholder="请选择资源所属村"
              clearable
              @change="change"
            />
          </el-form-item>

          <el-form-item
            label="所属组"
            prop="group"
          >
            <el-select
              v-model.number="ruleForm.group"
              placeholder="请选择所属组"
              clearable
            >
              <el-option
                v-for="item in groupAtt"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="资源类型"
            prop="type"
          >
            <el-select
              v-model.number="ruleForm.type"
              placeholder="请选择资源类型"
              clearable
            >
              <el-option
                v-for="item in typeAtt"
                :key="item.id"
                :label="`资源类型: ${item.name}`"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="资源名称"
            prop="name"
          >
            <el-input
              v-model="ruleForm.name"
              placeholder="请输入资源名称"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="所在位置"
            prop="position"
          >
            <el-input
              v-model="ruleForm.position"
              type="textarea"
              placeholder="请输入资源所在位置"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="占地面积"
            prop="footprint"
          >
            <el-input
              v-model="ruleForm.footprint"
              type="textarea"
              placeholder="请输入资源占地面积"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="简介"
            prop="explanation"
          >
            <el-input
              v-model="ruleForm.explanation"
              type="textarea"
              placeholder="请输入资源简介"
              clearable
            />
          </el-form-item>
          <el-form-item
            label="资源图片"
            prop="image"
          >
            <el-upload
              :file-list="ruleForm.image"
              list-type="picture-card"
              :action="uploadUrl"
              :headers="getAuthHeaders()"
              :on-success="handleSuccess"
              :on-remove="handleRemove"
              multiple
              accept=".Webp,.baiBMP,.PCX,.TIF,.GIF,.JPEG,.JPG,.TGA,.EXIF,.FPX,.SVG,.PSD,.CDR,.PCD,.DXF,.UFO,.EPS,.AI,.PNG,.HDRI,.RAW,.WMF,.FLIC,.EMF,.ICO,"
            >
              <i class="el-icon-plus" />
            </el-upload>
            <el-dialog
              :visible.sync="dialogVisible"
              size="tiny"
            >
              <img
                width="100%"
                :src="dialogImageUrl"
                alt
              >
            </el-dialog>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              @click="submitForm('ruleForm')"
            >
              {{ !id ? "立即创建" : "保存编辑" }}
            </el-button>
            <el-button @click="resetForm('ruleForm')">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
//手动添加
import { mapGetters } from "vuex";
export default {
  name: "Form",
  props: {
    id: {},
  },
  data() {
    return {
      ruleForm: {

        villageWrap: [],
        village: [],
        group: "",
        name: "",
        type: "",
        explanation: "",
        footprint: "",
        position: "",
        image: [],
      },
      rules: {
        villageWrap: [
          { required: true, message: "请选择资源所属村", trigger: "change" },
        ],
        type: [
          { required: true, message: "请选择资源类型", trigger: "change" },
        ],
        name: [
          { required: true, message: "请输入资源名称", trigger: "blur" },
        ],
        position: [
          { required: false, message: "请输入资源所在位置", trigger: "blur" },
        ],
        footprint: [
          { required: false, message: "请输入资源所在位置", trigger: "blur" },
        ],
        explanation: [
          { required: false, message: "请输入资源简介", trigger: "blur" },
        ],
        image: [
          { required: false, message: "请选择资源类型", trigger: "change" },
        ], 
      },
      options: [],
      dialogImageUrl: "",
      dialogVisible: false,
      createForm: {},
      villageCascader: [],
      groupAtt: [],
      villageProp: {
        value: "id",
        label: "name",
      },
      typeAtt: [],
      fileList: [],
    };
  },
  computed: {
    ...mapGetters({
      user: "user/info",
    }),
  },
  async created() {
    this.init();
    this.id && this.fetchData(this.id);
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid && this.id) {
          // alert("submit!");
          this.edit()
        } else if(valid && !this.id) {
          // return false;
          this.create();
        } else {
          return false
        }
      });
    },
    handleSuccess(res, file, fileList) {
      let att = []
      fileList.forEach(file =>  att.push(file.response ? file.response : file))
      this.fileList = att
    },
    handleRemove(file, fileList) {
      let att = []
      fileList.forEach(file =>  att.push(file.response ? file.response : file))
      this.fileList = att
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    resPip() {
      this.createForm = JSON.parse(JSON.stringify(this.ruleForm));
      this.createForm.image = this.fileList
      this.clearNullField(this.createForm, 'group')
    },
    async create() {
      this.resPip();
      const res = await this.$http.post(`/resources`, this.createForm);
      if (res.status == 201) {
        this.$baseMessage("新增成功", "success");
        this.$router.push({ name: "Resources" });
      } else {
        this.$baseMessage("新增失败", "error");
      }
    },
    async edit() {
      this.resPip();
      const res = await this.$http.put(`/resources/${this.id}`, this.createForm);
      if (res.status == 200) {
        this.$baseMessage("修改成功", "success");
        this.$router.push({ name: "Resources" });
      } else {
        this.$baseMessage("修改失败", "error");
      }
    },
    async fetchData(id) {
      const res = await this.$http.get(`resources/${id}?join=type&join=village&join=group`);

      const town = await this.$http.get(`village/${res.data.village.id}?join=town`);

      const area = await this.$http.get(`town/${town.data.town.id}?join=area`);
      res.data.villageWrap = [
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ];
      //手动触发 查找 资源类型
      this.change([
        area.data.area.id,
        town.data.town.id,
        res.data.village.id,
      ])

      res.data.group = res.data.group && res.data.group.id
      
      this.ruleForm = Object.assign({}, res.data);

      //强制图片赋值
      this.fileList = res.data.image || []
      //类型赋值
      this.ruleForm.type = res.data.type.id
      // this.town =
      console.log(this.ruleForm, res.data);
    },
    async init() {
      const res = await this.$http.get(`area?join=town&join=town.village`);
      res.data.forEach(area => {
        area.children = area.town
        area.town.forEach(town => {
          town.children = town.village
        })
      })
      this.villageCascader = res.data;
      this.setSelectItem()
    },
    async change(val) {
      this.ruleForm.village = val[val.length - 1];
      this.ruleForm.type = "";
      const res = await this.$http.get(`village/${this.ruleForm.village}?join=resourcesType&join=group`);
      this.typeAtt = res.data.resourcesType
      this.groupAtt = res.data.group
    },

    setSelectItem() {
      if(this.user.level < 1) {
      } else if (this.user.level == 1) {
        //区级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                town.disabled = true
              });
            }
          }
        });
      } else if (this.user.level == 2) {
        //镇级
        this.villageCascader.forEach((area) => {
          if(area.id == this.user.area.id) {
            area.disabled = false
             if (area.town.length > 0) {
              area.town.forEach((town) => {
                if(town.id == this.user.town.id) {
                  town.disabled = false
                } else {
                  town.disabled = true
                }
              });
            }
          } else {
            area.disabled = true
            if (area.town.length > 0) {
              area.town.forEach((town) => {
                  town.disabled = true
              });
            }
          }
        });
      } 
        else if (this.user.level == 3) {
          //村级
        this.ruleForm.village = this.user.village.id
        this.change([this.ruleForm.village])
      } 
    },
  },
};
</script>
